<?php
/**
 * 用户商品功能
 */

namespace app\api\controller\user;

use app\api\controller\Common;
use app\api\model\user\Goodsmodel;
class Goods extends Common {
    protected $data;
    public function initialize()
    {
        parent::initialize();
        $this->checkUserLogin(); // 验证登录
        $this->data = $this->request->except(['sign','accessKey','token']);
    }

    /**
     * 发布求购需求
     */
    public function goodsNeed(){
        $uid = $this->user['id'];
        $data = $this->data;
        $data_db['uid'] = $uid;
        $pics_data = $this->request->file('pics');
        if($data['brand_id'] && $data['name'] && $data['people'] && $pics_data){
            $pics_arr = [];
            foreach ($pics_data as $key=>$file){
                $info = $file->move('/public/uploads');
                if($info){
                    array_push($pics_arr,'/uploads/' .$info->getSaveName());
                }
            }
            $data_db['pics'] = $pics_arr;
            $data_db['brand_id'] = $data['brand_id'];
            $data_db['name'] = $data['name'];
            $data_db['code'] = $data['code'];
            $data_db['price'] = $data['price'];
            $data_db['send_time'] = $data['send_time'];
            $data_db['people'] = $data['people'];
            $data_db['create_time'] = date('Y-m-d H:i:s');
            $model = new Goodsmodel();
            $res = $model->sendGoodsNeed($data_db);
            if($res){
                $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'发布成功'];
            }else{
                $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'发布失败'];
            }
        }else{
            $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'请填写完整'];
        }
        return $this->show($this->return);
    }

    /**
     * 现货出价 - 生成商品+生成订单
     */
    public function spotGoodsAndOrder(){
        $uid = $this->user['id'];
        $where = [
            'id' => $uid,
            'type' => 2,
            'sale_status' => 2
        ];
        $is_sale = db('users')->where($where)->find();
        if($is_sale){
            $gid = $this->data['id'];
            $sku_key = $this->data['sku_key'];
            $sku_value = $this->data['sku_value'];
            $sale_price = $this->data['sale_price'];
            if($gid && $sku_key && $sku_value && $sale_price){
                $goods_base_info = db('goods_info')->where('id',$gid)->find();
                if($goods_base_info){
                    $sku = $sku_key . '#' . str_replace(',','-',$sku_value);
                    // 新增一个下架的商品，支付后上架
                    $insert_data = [
                        'name' => $goods_base_info['name'],
                        'code' => $goods_base_info['code'],
                        'brand_id' => $goods_base_info['brand_id'],
                        'category_one' => $goods_base_info['category_one'],
                        'category_two' => $goods_base_info['category_two'],
                        'sale_price' => $sale_price,
                        'original_price' => $goods_base_info['original_price'],
                        'stock' => 1,
                        'status' => 2,
                        'content' => $goods_base_info['content'],
                        'make_date' => $goods_base_info['make_date'],
                        'life_date' => $goods_base_info['life_date'],
                        'sku' => $sku,
                        'people' => $goods_base_info['people'],
                        'push_uid' => $uid,
                        'create_time' => date('Y-m-d H:i:s')
                    ];
                    $insert_goods_id = db('goods_info')->insertGetId($insert_data);
                    if($insert_goods_id){
                        $sku_data = [
                            'gid' => $insert_goods_id,
                            'desc' => $sku_value,
                            'price' => $sale_price,
                            'stock' => 1
                        ];
                        $sku_id = db('goods_info_sku')->insertGetId($sku_data);
                        $pic_data = db('goods_info_pic')->where('gid',$gid)->select();
                        if($pic_data){
                            $pic_insert_data = [];
                            foreach ($pic_data as $key=>$vo){
                                $pic_insert_data[$key]['gid'] = $insert_goods_id;
                                $pic_insert_data[$key]['pic'] = $vo['pic'];
                                $pic_insert_data[$key]['create_time'] = date('Y-m-d H:i:s');
                            }
                            db('goods_info_pic')->insertAll($pic_insert_data);
                        }
                        // 生成唯一订单号
                        $order_id = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
                        $service_price = $this->getSpotServicePrice($sale_price);
                        $order_data = [
                            'order_id' => $order_id,
                            'gid' => $insert_goods_id,
                            'sku_id' => $sku_id,
                            'uid' => $uid,
                            'order_price' => $sale_price,
                            'goods_num' => 1,
                            'buy_deposit' => $service_price['deposit'],
                            'buy_technology' => $service_price['technology'],
                            'buy_transfer' => $service_price['transfer'],
                            'buy_check' => $service_price['check'],
                            'buy_identify' => $service_price['identify'],
                            'buy_pack' => $service_price['pack'],
                            'order_status' => 1,
                            'order_time' => date('Y-m-d H:i:s')
                        ];
                        $spot_order_id = db('spot_order_info')->insertGetId($order_data);
                        if($spot_order_id){
                            $return_data = [
                                'order_id' => $spot_order_id,
                            ];
                            $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'OK','data'=>$return_data];
                        }else{
                            // 创建订单失败，删除商品与sku+图片
                            db('goods_info')->where('id',$insert_goods_id)->delete();
                            db('goods_info_sku')->where('id',$sku_id)->delete();
                            db('goods_info_pic')->where('gid',$insert_goods_id)->delete();
                            $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'出价失败'];
                        }
                    }else{
                        $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'出价失败'];
                    }
                }else{
                    $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'获取商品错误'];
                }
            }else{
                $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'请选商品择规格'];
            }
        }else{
            $this->return = ['status'=>200,'code'=>'NO_SELLER','message'=>'您不是卖家'];
        }
        return $this->show($this->return);
    }

    /**
     * 现货出价扣费计算
     */
    public function getSpotServicePrice($price){
        $return = [];
        $info = db('spot_service_price')->where('id',1)->find();
        $deposit = $info['deposit'] * $price;
        $return['deposit'] = $deposit > 28 ? $deposit : 28;
        $return['technology'] = $info['technology'];
        $return['transfer'] = $info['transfer'] * $price;
        $return['check'] = $info['check'];
        $return['identify'] = $info['identify'];
        $return['pack'] = $info['pack'];
        return $return;
    }

    public function spotServicePirce(){
        $info = db('spot_service_price')->where('id',1)->find();
        $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'OK','data'=>$info];
        return $this->show($this->return);
    }

    /**
     * 查询现货出价详情
     */
    public function spotDetail(){
        $order_id = $this->data['order_id'];
        if($order_id){
            $order_info = db('spot_order_info')->where('id',$order_id)->find();
            if($order_info){
                $goods_info = db('goods_info')->field('id,name')->where('id',$order_info['gid'])->find();
                $pic = db('goods_info_pic')->where('gid',$order_info['gid'])->value('pic');
                $sku = db('goods_info_sku')->where('gid',$order_info['gid'])->value('desc');
                $order_info['goods_info']['id'] = $goods_info['id'];
                $order_info['goods_info']['name'] = $goods_info['name'];
                $order_info['goods_info']['pic'] = $pic;
                $order_info['goods_info']['desc'] = $sku;
                $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'OK','data'=>$order_info];
            }else{
                $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'查询失败'];
            }
        }else{
            $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'缺少订单号'];
        }
        return $this->show($this->return);
    }

    /**
     * 查询现货出价订单列表（停用）
     */
    public function spotOrderList(){
        $uid = $this->user['id'];
        if($uid){
            $order_info = db('spot_order_info')->where('uid',$uid)->select();
            if($order_info){
                foreach ($order_info as $key=>$vo){
                    $goods_info = db('goods_info')->field('id,name')->where('id',$vo['gid'])->find();
                    $pic = db('goods_info_pic')->where('gid',$vo['gid'])->value('pic');
                    $sku = db('goods_info_sku')->where('gid',$vo['gid'])->value('desc');
                    $order_info[$key]['goods_info']['id'] = $goods_info['id'];
                    $order_info[$key]['goods_info']['name'] = $goods_info['name'];
                    $order_info[$key]['goods_info']['pic'] = $pic;
                    $order_info[$key]['goods_info']['desc'] = $sku;
                }
                $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'OK','data'=>$order_info];
            }else{
                $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'没有订单'];
            }
        }else{
            $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'缺少登录信息'];
        }
        return $this->show($this->return);
    }

    /**
     * 订单支付保证金，与调价
     */
    public function orderDepositPay(){
        $order_id = $this->data['order_id'];
        $price = $this->data['price'];
        $pay_method = $this->data['pay_method'];
        if($order_id && $price && $pay_method){
            $info = db('spot_service_price')->where('id',1)->find();
            $deposit_base = $info['deposit'] * $price;
            $deposit = $deposit_base > 28 ? $deposit_base : 28;
            $transfer = $info['transfer'] * $price;
            $order_data = [
                'order_price' => $price,
                'pay_method' => $pay_method,
                'buy_deposit' => $deposit,
                'buy_transfer' => $transfer
            ];
            $order_status = db('spot_order_info')->where('id',$order_id)->value('order_status');
            if($order_status == 2){ // 已支付保证金,标记为调价
                $order_data['is_change_price'] = 1;
            }
            db('spot_order_info')->where('id',$order_id)->update(['order_price'=>0]);
            $order_info = db('spot_order_info')->where('id',$order_id)->update($order_data);
            if($order_info){
                // TODO 根据支付方式调用支付,这里默认成功
                $order_data = [
                    'order_status' => 2,
                    'pay_time' => date('Y-m-d H:i:s')
                ];
                db('spot_order_info')->where('id',$order_id)->update($order_data);
                $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'OK'];
            }else{
                $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'支付失败'];
            }
        }else{
            $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'缺少参数'];
        }
        return $this->show($this->return);
    }

    /**
     * 现货出价 - 发货
     */
    public function sendOut(){
        $order_id = $this->data['order_id'];
        $express_id = $this->data['express_id'];
        $express_num = $this->data['express_num'];
        if($order_id && $express_id && $express_num){
            $update_data = [
                'express_id' => $express_id,
                'express_num' => $express_num
            ];
            $res = db('spot_goods_info')->where('id',$order_id)->update($update_data);
            if($res){
                $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'OK'];
            }else{
                $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'发货失败'];
            }
        }else{
            $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'缺少参数'];
        }
        return $this->show($this->return);
    }

    /**
     * 取消订单
     */
    public function cancelOrder(){
        $order_id = $this->data['order_id'];
        if($order_id){
            $order_info = db('spot_order_info')->where('id',$order_id)->find();
            if($order_info['order_status'] == 1){ // 待支付保证金
                $order_data = ['order_status'=>5];
                $order_info = db('spot_order_info')->where('id',$order_id)->update($order_data);
                if($order_info){
                    $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'OK','data'=>1];
                }else{
                    $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'取消失败'];
                }
            }elseif($order_info['order_status'] == 2){ // 已支付保证金
                $order_data = ['order_status'=>5];
                $order_info = db('spot_order_info')->where('id',$order_id)->update($order_data);
                if($order_info){
                    // 退还保证金到余额
                    db('users')->where('id',$order_info['uid'])->setInc('account',$order_info['buy_deposit']);
                    $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'OK','data'=>2];
                }else{
                    $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'取消失败'];
                }
            }elseif($order_info['order_status'] == 3){ // 买家已支付
                $order_data = ['order_status'=>5];
                $order_info = db('spot_order_info')->where('id',$order_id)->update($order_data);
                if($order_info){
                    $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'OK','data'=>3];
                }else{
                    $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'取消失败'];
                }
            }else{
                $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'无法取消'];
            }
        }else{
            $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'缺少参数'];
        }
        return $this->show($this->return);
    }

}